#!/bin/bash
#
# VM monitor and limiter by Vladislav Belogrudov
# vlad.belogrudov@gmail.com
# 


if [[ 2 -gt $# ]]
then
    echo "I need arguments! please specify vm name and a list of cpuload,time pairs, e.g. $0 c1 10,20 30,45"
    exit 1
fi

user=openstack
controller=172.16.0.1
vm=$1
shift
loads="$@"

echo vm name = $vm, load shape: $loads

while true
do
    for pair in $loads
    do
        # echo "current load pair = $pair"
        set -- `echo $pair | tr ',' ' '`
        mylimit=$1 
        [[ $mylimit -eq 0 ]] && mylimit=1
        mytime=$2
        echo "running at $mylimit% for $mytime seconds"
        vminfo=`ssh $user@$controller "nova show $vm | grep -E 'instance_name|OS-EXT-SRV-ATTR:host' | tr -s ' ' | cut -d \  -f 4"`
        set -- `echo $vminfo`
        host=$1
        instance=$2
        echo host = $host, instance = $instance
        vmpid=`ssh $user@$host "ps -o pid=,args= -C qemu-system-x86_64 | grep ' -name $instance ' | cut -d \  -f 1"`  
        echo killing old limit 
        limpid=ssh $user@$host "ps -o pid=,args= -C cpulimit | grep ' -p $vmpid ' | cut -d \  -f 1"
        echo limiter pid = $limpid
        ssh $user@$host "sudo kill -9 $limpid"
        echo setting new limit
        ssh $user@$host "sudo nohup cpulimit -p $vmpid -l $mylimit &> /tmp/x.log &"
        echo sleeping $mytime
        sleep $mytime
    done
done
